#include "adc.h"

#define ADC_RAW_PATH    "/sys/bus/iio/devices/iio:device0/in_voltage3_raw"
#define fifo2_path   "/home/debian/qt_test/fifo2"

extern u_int8_t tx_data[6];

union {
 int fa;
 unsigned char farray[4];
}utemp;

int adc_dev_init(void)
{
    
    // printf("adc11\n");

    int fd, fifo2_fd, ret;
    u_int8_t val_raw[4];
    int i = 0;
    // u_int8_t data_f;

    fifo2_fd = open(fifo2_path, O_RDWR);
    if( fifo2_fd < 0 ){
        printf("code FIFO2 file open error!\n");
        exit(-1);
    }

    // printf("adc222\n");

    fd = open(ADC_RAW_PATH, O_RDONLY);
    if( fd < 0 ){
        printf("adc dev file open error!\n");
        return -1;
    }

    // printf("adc333\n");

    while(1){
        if( read(fd, val_raw, 4) > 0){
            //设备号0x03

            // utemp.fa = (atoi(val_raw) / 805.664);
            utemp.fa = atoi(val_raw);

            printf("utemp.fa = %d\n", utemp.fa);

            tx_data[1] = 0x03;

            for(i=2; i<6; i++){
                tx_data[i] = utemp.farray[i-2];
                printf("%x", tx_data[i]);
            }
            // tx_data[2] = utemp.farray[3];
            // tx_data[3] = utemp.farray[2];
            // tx_data[4] = utemp.farray[1];
            // tx_data[5] = utemp.farray[0];

            printf("\n");

            tx_data[6] = ((tx_data[1]+tx_data[2]+tx_data[3]+tx_data[4]+tx_data[5])&0xff);

            ret = write(fifo2_fd, tx_data, 8);

            if( ret != 8 ){
                printf("adc data write error! only write %d byte\n",ret);
            }

            lseek(fd, 0, SEEK_SET);
            for(i=0; i<8; i++){
                printf("%x ",tx_data[i]);
            }
            printf("\n");
            
        }
        printf("adc\n");
        usleep(500*1000);     
    }
    

}



